import { ProcessService } from './../../../@core/services/process/process.service';
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DataTableComponent, DialogService, TableWidthConfig } from 'ng-devui';
import { concatMap } from 'rxjs';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';

@Component({
  selector: 'app-process-item',
  templateUrl: './process-item.component.html',
  styleUrls: ['./process-item.component.scss']
})
export class ProcessItemComponent {
  tabledata:any;//编码规则
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  checkedIds = [];
  pageSizeOptions = [10, 20, 30, 50, 100];
  msgs: { severity: any; summary: any; content: any; }[];
  config = {
    id: 'Add-Dirctoy-Type',
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  SearchTerm:string='';
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  checkboxList = [];
  allChecked = false;
  halfChecked = false;
  file: any;
  constructor(private EncodeRulesService:EncodeRulesService,private Router:Router,private dialogService: DialogService,private SharedMethodService:SharedMethodService,private ProcessService:ProcessService){}
  ngOnInit(): void {
    this.ProcessService.GetPagedProcesss(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.pager.total=data.totalCount;
    })//获取工序
  }
  dataTableOptions = {
    columns: [
      {
        field: 'showType',
        header: '工序编码',
        fieldType: 'text'
      },
      {
        field: 'type',
        header: '工序名称',
        fieldType: 'text'
      },
      {
        field: 'enabled',
        header: '备注',
        fieldType: 'boolean'
      }
    ]
  };//表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field:'caozuo',
      width:'150px'
    },
    {
      field: 'showType',
      width: '250px'
    },
    {
      field: 'type',
      width: '250px'
    },
    {
      field: 'enabled',
      width: '150px'
    }
  ];//表格宽度配置
  pageIndexChange($event: any) {
    this.pager.pageIndex=$event;
    this.ProcessService.GetPagedProcesss(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
    })//获取工序
  }//切换页码
  pageSizeChange($event: any){
    this.ProcessService.GetPagedProcesss(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
    })//获取工序
  }//改变每页显示数量
  Delete(id:any,dialogtype?:string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该道工序？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
              this.ProcessService.DeleteProcesss([id]).subscribe((data:any)=>{
                results.modalInstance.hide();
                this.showToast('success','删除成功','该工序删除成功')
                this.checkedIds=[];
                this.ProcessService.GetPagedProcesss(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.tabledata=data.items;
                  this.pager.total=data.totalCount;
                })//获取工序
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
              )
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//删除
  Deletes(id:any,dialogtype?:string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该道工序？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
              this.ProcessService.DeleteProcesss(this.checkedIds).subscribe((data:any)=>{
                results.modalInstance.hide();
                this.showToast('success','删除成功','该工序删除成功')
                this.checkedIds=[];
                this.ProcessService.GetPagedProcesss(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.tabledata=data.items;
                  this.pager.total=data.totalCount;
                })//获取工序
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
              )
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//删除
  edit(id:any){
    this.Router.navigate(['/pages/process/process-item/edit-process', id], {
      queryParams: { tabActiveId: '基本信息' }
    });
  }//编辑
  filter(){
    this.pager.pageIndex=1;
    this.ProcessService.GetPagedProcesss(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
    })//获取工序
  }//筛选
  reset(){
    this.SearchTerm='';
    this.ProcessService.GetPagedProcesss(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
    })//获取工序
  }//重置
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  cleared(){
    this.SharedMethodService.cleared(this.checkedIds,this.tabledata,this.datatable).subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable);
  }//单选
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable,'processId').subscribe((data:any)=>{
      this.checkedIds=data;

    })
  }//获取选中行
  editUser(id: any) {
    this.Router.navigate(['/pages/process/process-item/edit-process', id], {
      queryParams: { tabActiveId: '关联人员' }
    });
  }//编辑人员
  editDevice(id: any) {
    this.Router.navigate(['/pages/process/process-item/edit-process', id], {
      queryParams: { tabActiveId: '关联设备' }
    });
  }//编辑设备
  importFormExcel(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.ProcessService.ImportProcessesFromExcel(this.file).pipe(
      concatMap((data: any) => {
        // 显示成功提示
        this.showToast('success', '成功', '导入成功');
        return  this.ProcessService.GetPagedProcesss(this.SearchTerm,this.pager.pageIndex,this.pager.pageSize)
      })
    ).subscribe(
      (data: any) => {
        this.tabledata = data.items;
        this.pager.total = data.totalCount
      },
      (error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      },
      () => {
        // 无论成功还是失败都清除文件选择
        event.target.value = null;
      }
    );
  }
  @ViewChild('fileInput1') fileInput1: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput1.nativeElement.click();
  }
  DownloadWarehouse(){
    this.ProcessService.DownloadProcessFile().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '工序信息.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载员工信息
  DownloadModel(){
    this.ProcessService.DownloadProcessFileModel().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '工序模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载模板
}
